package com.xiuxia.bopicturebackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.xiuxia.bopicturebackend.common.ColorTransformUtils;
import com.xiuxia.bopicturebackend.common.ImageUtils;
import com.xiuxia.bopicturebackend.common.MinIOUtil;
import com.xiuxia.bopicturebackend.config.CosClientConfig;
import com.xiuxia.bopicturebackend.config.MinioConfig;
import com.xiuxia.bopicturebackend.exception.BusinessException;
import com.xiuxia.bopicturebackend.exception.ErrorCode;
import com.xiuxia.bopicturebackend.manager.CosManager;
import com.xiuxia.bopicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    @Resource
    private MinIOUtil minIOUtil;

    @Resource
    private MinioConfig minioConfig;


    /**
     * minio专用
     * @param inputSource
     * @param uploadPathPrefix
     * @return
     */
   /* public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1.校验图片
        validPicture(inputSource);
        String uuid = RandomUtil.randomString(16);
        // 2.获取原始文件名
        String originalFilename = getOriginFilename(inputSource);
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, (StrUtil.isEmpty(FileUtil.getSuffix(originalFilename)) ? "webp" : FileUtil.getSuffix(originalFilename)));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        //解析结果并返回
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            // 3.处理输入源并生成本地临时文件
            processFile(inputSource, file);
            // 上传图片
            String uploadUrl = minIOUtil.upload(file, uploadPath);
            // 获取图片详细信息
            if (StrUtil.isEmpty(uploadUrl)) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
            }
            return buildResult(originalFilename, file, uploadUrl);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 清理临时文件
            this.deletePicture(file);
        }
    }*/
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1.校验图片
        validPicture(inputSource);
        String uuid = RandomUtil.randomString(16);
        // 2.获取原始文件名
        String originalFilename = getOriginFilename(inputSource);
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, (StrUtil.isEmpty(FileUtil.getSuffix(originalFilename)) ? "webp" : FileUtil.getSuffix(originalFilename)));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        //解析结果并返回
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            processFile(inputSource, file);
            // 3.处理输入源并生成本地临时文件
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollUtil.isNotEmpty(objectList)) {
                CIObject ciObject = objectList.get(0);
                CIObject thumbnailCiObject =ciObject;
                if (objectList.size()>1){
                    thumbnailCiObject = objectList.get(1);
                }
                return buildResult(originalFilename, ciObject,thumbnailCiObject,uploadPath,imageInfo);
            }
            return buildResult(imageInfo, uploadPath, originalFilename, file);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 清理临时文件
            this.deletePicture(file);
        }
    }
    /**
     * 校验输入源（本地文件或 URL）
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 封装返回结果
     *
     * @param imageInfo        图片详情信息
     * @param uploadPath       上传路径
     * @param originalFilename 原始文件名
     * @param file             本地临时文件
     * @return
     */
    private UploadPictureResult buildResult(ImageInfo imageInfo, String uploadPath, String originalFilename, File file) {
        // 封装返回结果
        String format = imageInfo.getFormat();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicColor(ColorTransformUtils.getStandardColor(imageInfo.getAve()));
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());

        return uploadPictureResult;
    }

    private UploadPictureResult buildResult(String originFilename, CIObject compressedCiObject, CIObject thumbnailCiObject, String uploadPath, ImageInfo imageInfo) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicColor(ColorTransformUtils.getStandardColor(imageInfo.getAve()));
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        // 设置图片为压缩后的地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        // 设置缩略图的地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        uploadPictureResult.setOriginalUrl(cosClientConfig.getHost() + "/" + uploadPath);
        return uploadPictureResult;
    }

    protected UploadPictureResult buildResult(String originFilename, File file, String objectName) {
        try {
            BufferedImage image = javax.imageio.ImageIO.read(file);
            //文件后缀
            String fileSuffix = StrUtil.isEmpty(FileUtil.getSuffix(originFilename)) ? "webp" : FileUtil.getSuffix(originFilename);
            int picWidth = image.getWidth();
            int picHeight = image.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

            // 解析 objectName 路径
            int lastSlashIndex = objectName.lastIndexOf("/");
            String dirPath = objectName.substring(0, lastSlashIndex);
            String filename = objectName.substring(lastSlashIndex + 1);
            int dotIndex = filename.lastIndexOf(".");
            String baseName = filename.substring(0, dotIndex);


            // 1. 压缩图（保留原尺寸）
            byte[] compressedBytes = ImageUtils.compress(image, "webp", 0.5f); // 80% 质量
            String compressedObjectName = String.format("/%s/%s_compressed.%s", dirPath, baseName, fileSuffix);
            String compressedUrl = minIOUtil.upload(compressedBytes, compressedObjectName);
            String thumbnailUrl = compressedUrl;
            // 2. 缩略图（200x200）
            if (file.length() > 2 * 1024) {
                byte[] thumbnailBytes = ImageUtils.resize(image, 256, 256, fileSuffix);
                String thumbnailObjectName = String.format("/%s/%s_thumbnail.%s", dirPath, baseName, fileSuffix);
                thumbnailUrl = minIOUtil.upload(thumbnailBytes, thumbnailObjectName);
            }
            UploadPictureResult result = new UploadPictureResult();
            result.setUrl(minioConfig.getUrl() + "/" + minioConfig.getBucket() + compressedUrl);
            result.setThumbnailUrl(minioConfig.getUrl() + "/" + minioConfig.getBucket() + thumbnailUrl);
            result.setOriginalUrl(minioConfig.getUrl() + "/" + minioConfig.getBucket() + objectName);
            result.setPicName(FileUtil.mainName(originFilename));
            result.setPicSize(file.length());
            result.setPicWidth(picWidth);
            result.setPicHeight(picHeight);
            result.setPicScale(picScale);
            result.setPicFormat(fileSuffix);

            return result;
        } catch (Exception e) {
            log.warn("读取图片信息失败", e);
            return fallbackBuildResult(originFilename, file, objectName);
        }
    }

    /**
     * 图片信息获取失败时的降级构建方法
     */
    protected UploadPictureResult fallbackBuildResult(String originFilename, File file, String objectName) {
        UploadPictureResult result = new UploadPictureResult();
        result.setUrl(minioConfig.getUrl() + "/" + minioConfig.getBucket() + objectName);
        result.setPicName(FileUtil.mainName(originFilename));
        result.setPicSize(file.length());
        result.setPicFormat(FileUtil.getSuffix(originFilename));
        return result;
    }

    /**
     * 删除临时文件
     *
     * @param file 文件
     */
    public void deletePicture(File file) {
        if (file == null) return;
        boolean deleteResult = file.delete();
        if (!deleteResult) log.error("file delete error, file path = {}", file.getAbsolutePath());
    }


}
